package org.soretro.portfolio.view.videoPlayer
{
	import com.google.analytics.AnalyticsTracker;
	import com.google.analytics.GATracker;
	import com.greensock.TweenLite;
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.net.LocalConnection;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.system.Security;
	
	import mx.events.ResizeEvent;
	import mx.managers.SystemManager;
	
	import org.robotlegs.mvcs.Mediator;
	import org.soretro.portfolio.controller.events.WorkItemEvent;
	import org.soretro.portfolio.helpers.GoogleAnalytics;
	import org.soretro.portfolio.view.videoPlayer.events.VideoPlayerEvent;
	
	public class VideoMediator extends Mediator
	{
		[Inject]
		public var view:VideoView;
		
		[Bindable]
		protected var player:Object;
		
//		protected var youTube:YouTubeFeedClient;
		protected var loader:Loader = new Loader();
		private var youTubeId:String;
		public var tracker:AnalyticsTracker;
		
		override public function onRegister():void
		{
			googleTracker();
			
			view.alpha = 0;
			setupSecurity();
			
			var lc:LocalConnection = new LocalConnection();
			if ( lc.domain.toString() == "localhost" ) {
				view.editBttn.visible = true;
			} else {
				view.editBttn.visible = false;
			}
			
			view.pageTitle = "VIDEO PLAYER";
			
//			youTube = YouTubeFeedClient.getInstance();
			
			view.closeBttn.addEventListener(MouseEvent.CLICK, closeButtonClicked);
			view.editBttn.addEventListener(MouseEvent.CLICK, editButtonClicked);
			view.addEventListener(ResizeEvent.RESIZE, onResize);
			
			eventMap.mapListener(eventDispatcher, VideoPlayerEvent.SHOW_VIDEO, showVideo);
			eventMap.mapListener(eventDispatcher, VideoPlayerEvent.HIDE_VIDEO, hideVideo);
			
			loadVideoPlayer();
		}
		
		private function play(event:WorkItemEvent):void
		{
//			showVideo( event );
		}
		
		protected function loadVideoPlayer():void
		{
			loader.load(new URLRequest("http://www.youtube.com/v/3Q1-L7PJ-DA?version=3&fs=1&showinfo=0&modestbranding=0&rel=0&autohide=1&theme=light&color=white"));
			loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit);
		}
		protected function onLoaderInit(event:Event):void {
			loader.content.addEventListener("onReady", onPlayerReady);
			loader.content.addEventListener("onError", onPlayerError);
			loader.content.addEventListener("onStateChange", onPlayerStateChange);
			loader.content.addEventListener("onPlaybackQualityChange", onVideoPlaybackQualityChange);
		}
		
		protected function onPlayerReady(event:Event):void
		{
			trace("player ready:", Object(event).data);
			
			player = loader.content;
			//				player.setSize(240, 210);
			view.swfLoader.addEventListener(flash.events.IOErrorEvent.IO_ERROR , onSWFLoaderIoError);
			view.swfLoader.autoLoad = true;
			view.swfLoader.scaleContent = true;
			view.swfLoader.maintainAspectRatio = true;
			view.swfLoader.load(player);
			
			onResize();
			//				playWorkItem(); // Play automatically.
		}
		
		protected function onResize(event:ResizeEvent = null):void
		{
			if (!player) return;
			
			view.swfLoader.width = view.videoHolder.width;
			view.swfLoader.height = view.videoHolder.height;
		}
		
		protected function onSWFLoaderIoError(event:IOErrorEvent):void
		{
		}
		
		protected function onVideoPlaybackQualityChange(event:Event):void
		{
		}
		
		protected function onPlayerStateChange(event:Event):void
		{
		}
		
		protected function onPlayerError(event:Event):void
		{
		}
		
		private function setupSecurity():void
		{
			Security.allowDomain("www.youtube.com");
			Security.allowDomain("youtube.com");
			Security.allowDomain("img.youtube.com"); 
			Security.loadPolicyFile("http://www.youtube.com/crossdomain.xml"); 
			Security.loadPolicyFile("http://img.youtube.com/crossdomain.xml");
			
			Security.allowDomain("s.ytimg.com"); 
			Security.allowDomain("i.ytimg.com"); 
			Security.allowDomain("i4.ytimg.com"); 
			Security.loadPolicyFile("http://s.ytimg.com/crossdomain.xml");
			Security.loadPolicyFile("http://i.ytimg.com/crossdomain.xml"); 
			Security.loadPolicyFile("http://i4.ytimg.com/crossdomain.xml");
			
			
//			Security.loadPolicyFile("*");
//			Security.allowDomain("*");
		}
		
		private function closeButtonClicked( event:MouseEvent ):void
		{
			GoogleAnalytics.getInstance().send( "Video/closed" );
//			tracker.trackPageview( "Video/closed" );
			trace("Video/closed");
			TweenLite.to( view, 0.6, { alpha:0, onComplete:closePage } );
		}
		
		private function editButtonClicked( event:MouseEvent ):void
		{
//			http://www.youtube.com/my_videos_edit?ns=1&video_id=dJAIymzBr20&next=%2Fmy_videos
			var url:String = "http://www.youtube.com/my_videos_edit?ns=1&video_id="+ youTubeId +"&next=%2Fmy_videos";
			var request:URLRequest = new URLRequest(url);
			
			try {
				navigateToURL(request, '_youTubeEditor');
			} catch (e:Error) {
				trace("YouTube editor error occurred!");
			}
		}
		
		public function playWorkItem( youTubeCode:String = null ):void
		{
			if ( player ) {
				player.cueVideoById( youTubeCode );
			} else {
				trace("player not set");
			}
//			player.playVideo();
		}
		
		public function stopWorkItem():void
		{
			if ( player ) {
				player.stopVideo();
			}
		}
		
		private function showVideo( event:VideoPlayerEvent ):void
		{
			youTubeId = event.youTubeId;
			
			trace(">>>> SHOW VIDEO <<<< = "+ youTubeId );
			
			view.alpha = 0;
			view.visible = true;
			TweenLite.to( view, 1, { alpha:1 } );
			playWorkItem( youTubeId );
			view.title.text = event.title;
			view.desc.text = event.desc;
		}
		
		private function hideVideo( event:VideoPlayerEvent ):void
		{
			trace(">>>> HIDE VIDEO <<<<");
			TweenLite.to( view, 0.6, { alpha:0, onComplete:closePage } );
		}
		
	
		private function closePage():void
		{
			view.visible = false;
			view.alpha = 0;
			stopWorkItem();
		}
		
		private function googleTracker():void
		{
			tracker = new GATracker( SystemManager.getSWFRoot(this).stage, "UA-18699334-1", "AS3", false );
		}
	}
}